import { defineStore } from "pinia";
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user/index";
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from "@/api/user/type";
//引入常量路由
import { constantRouterMap } from "@/router/router";
let useUserStore = defineStore("User", {
  state: () => {
    return {
      token: localStorage.getItem("TOKEN") || "", //用户唯一标识token
      menuRoutes: constantRouterMap, //仓库存储生成菜单需要的路由数据
      username: "", //用户名
      avatar: "", //用户头像
    };
  },
  actions: {
    // 登录
    async userLogin(data: loginFormData) {
      console.log("登录参数", data);
      let result: loginResponseData = await reqLogin(data);
      console.log("登录结果", result);
      if (result.code === 200) {
        this.token = result.data;
        localStorage.setItem("TOKEN", result.data);
        return "ok";
      } else {
        return Promise.reject(new Error(result.data));
      }
    },
    // 获取用户信息
    async userInfo() {
      let result: userInfoResponseData = await reqUserInfo();
      console.log("获取用户信息", result);
      if (result.code === 200) {
        this.username = result.data.name;
        this.avatar = result.data.avatar;
        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
    // 获取用户退出登录
    async userLogout() {
      let result: any = await reqLogout();
      console.log("退出登录", result);
      if (result.code === 200) {
        this.token = "";
        this.username = "";
        this.avatar = "";
        localStorage.removeItem("TOKEN");
        return "ok";
      }
    },
  },
  getters: {},
});
export default useUserStore;
